import Vue from 'vue'
import Vuex from 'vuex'
import axios from "axios"

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    goods: [],//商品数据
    cart: JSON.parse(localStorage.getItem("cart")) || [],//购物车数据
  },
  mutations: {
    getGoods(state, items) {
      state.goods = items
    },
    add_Cart(state, item) {
      //商品去重
      var result = true;
      state.cart.forEach(element => {
        if (element.id == item.id) {
          element.num++
          result = false
        }
      })
      if (result) {
        item.num = 1
        item.checked = false
        state.cart.push(item)
      }
      //同步本地
      localStorage.setItem("cart", JSON.stringify(state.cart))
      // localStorage.cart = JSON.stringify(state.cart)
    }
  },
  actions: {
    getGoods(context) {
      axios.get(" http://api.kudesoft.cn/tdk/goods")
        .then(res => {
          console.log(res.data.data.data.list)
          context.commit('getGoods', res.data.data.data.list)
        })
    },
    add_Cart(context, item) {
      context.commit('add_Cart', item)
    }
  },
  modules: {
  }
})
